import 'dart:convert';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/smart_home_water_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_folder_detail_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/category_data_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/style_data_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_simple_store_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_and_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_index_response_bean.dart';
import 'package:e_reception_flutter/utils/flutter_global_monitoring_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import '../smart_home_category_response_bean.dart';
import '../smart_home_style_type_bean.dart';
import 'column_data_response_bean.dart';


class SmartHomePublishViewModel extends BasePagerViewModel<
    SmartHomeIndexListItemBean,
    SmartHomeIndexResponseBean> {


  ValueNotifier<int> totalValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<ColumnDataBean> columnValueNotifier;

  ValueNotifier<SmartHomeWaterListDataBean> smartHomeWaterListValueNotifier;

  ValueNotifier<List<SmartHomeStoreAndTerminalListData>> smartHomeStoreAndTerminalListValueNotifier;
  ValueNotifier<List<SimpleStoreListBean>> simpleStoreListValueNotifier;

  SmartHomePublishViewModel(BaseState<StatefulWidget> state, {ColumnDataBean dataBean})
      : super(state){
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    totalValueNotifier = ValueNotifier(null);
    columnValueNotifier = ValueNotifier(dataBean??null);
    smartHomeWaterListValueNotifier = ValueNotifier(null);
    smartHomeStoreAndTerminalListValueNotifier = ValueNotifier(null);
    simpleStoreListValueNotifier = ValueNotifier(null);
  }

  ///智能家居发布动态
  void publish(){

  }


  ///新增栏目
  ///type 00新增 01编辑 02删除
  ///scid 智能家居栏目id（编辑、删除传）
  void createColumn(BuildContext context, String name, String shid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.SMART_HOME_ADD_EDIT_DELETE_COLUMN, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "name":name ?? "",
      "shid":shid ?? "",
      "scid":"",
      "type":"00",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///编辑分类
  ///type 00新增 01编辑 02删除
  ///stid 智能家居栏目id（编辑、删除传）
  void editColumn(BuildContext context, String name, String shid, String scid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.SMART_HOME_ADD_EDIT_DELETE_COLUMN, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "name":name ?? "",
      "shid":shid ?? "",
      "scid":scid??"",
      "type":"01",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///删除分类
  ///type 00新增 01编辑 02删除
  ///scid 智能家居栏目id（编辑、删除传）
  void deleteColumn(BuildContext context, String shid, String scid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.SMART_HOME_ADD_EDIT_DELETE_COLUMN, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid??"",
      "scid":scid??"",
      "type":"02",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///获取栏目
  void getColumnList(BuildContext context, String shid, String styles, String stids, String stnames){
    if(StringUtils.isEmpty(shid)){
      VgToastUtils.toast(context, "门店数据异常");
      return;
    }
    String cacheKey = NetApi.SMART_HOME_GET_COLUMN_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + shid + styles + stids + stnames;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取分类：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        SmartHomeColumnResponseBean bean = SmartHomeColumnResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            columnValueNotifier?.value = bean?.data;
          }
          loading(false);
        }
        getColumnOnLine(shid, styles, stids, stnames, cacheKey, bean);
      }else{
        getColumnOnLine(shid, styles, stids, stnames, cacheKey, null);
      }
    });
  }


  ///网络获取最新分类
  void getColumnOnLine(String shid, String styles, String stids, String stnames, String cacheKey, SmartHomeColumnResponseBean bean, {Function(List<ColumnListBean> columnList) onGetColumn}){
    VgHttpUtils.get(NetApi.SMART_HOME_GET_COLUMN_LIST, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "styles":styles??"",
      "stids":stids??"",
      "stnames":stnames??"",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeColumnResponseBean bean =
          SmartHomeColumnResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            if(bean != null && bean.data != null){
              columnValueNotifier?.value = bean?.data;
              if(bean?.data?.columnList != null && onGetColumn != null){
                onGetColumn.call(bean?.data?.columnList);
              }
            }
          }
          loading(false);
          if(bean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            print("缓存文件详情：" + cacheKey + "   " + json.encode(bean));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          if(bean == null){
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }
        }
    ));
  }

  ///分类排序
  void modifyCategory(BuildContext context, String orders, String stids){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(NetApi.MODIFY_CATEGORY_ORDER, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "orders":orders??"",
      "stids":stids??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///编辑封面
  void editFolderCover(BuildContext context, String coversize, String coverurl, String sfid, String shid){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(NetApi.EDIT_SMART_HOME_FOLDER_COVER, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "coversize":coversize??"",
      "coverurl":coverurl??"",
      "sfid":sfid??"",
      "shid":shid??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeFolderDetailEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }


  ///网络获取最新分类
  ///00类型 01空间 02风格
  void getLatestColumn(String shid, Function(List<ColumnListBean> columnList) onGetColumn){
    loading(true);
    VgHttpUtils.post(NetApi.SMART_HOME_GET_COLUMN_CATEGORY_STYLE_DATA, params: {
      "shid":shid ?? "",
      "type":"00",
    },callback: BaseCallback(
        onSuccess: (val){
          ColumnDataResponseBean bean =
          ColumnDataResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            if(bean != null && bean.data != null){
              if(bean?.data?.list != null && onGetColumn != null){
                onGetColumn.call(bean?.data?.list);
              }
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///网络获取最新分类
  ///00类型 01空间 02风格
  void getLatestCategory(String shid, Function(List<SpatialTypeListBean> categoryList) onGetCategory){
    loading(true);
    VgHttpUtils.post(NetApi.SMART_HOME_GET_COLUMN_CATEGORY_STYLE_DATA, params: {
      "shid":shid ?? "",
      "type":"01",
    },callback: BaseCallback(
        onSuccess: (val){
          CategoryDataResponseBean bean =
          CategoryDataResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
              if(bean?.data?.list != null && onGetCategory != null){
                onGetCategory.call(bean?.data?.list);
              }
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///网络获取最新风格
  ///00类型 01空间 02风格
  void getLatestStyle(String shid, Function(List<SmartHomeStyleTypeBean> styleList) onGeStyle){
    loading(true);
    VgHttpUtils.post(NetApi.SMART_HOME_GET_COLUMN_CATEGORY_STYLE_DATA, params: {
      "shid":shid ?? "",
      "type":"02",
    },callback: BaseCallback(
        onSuccess: (val){
          StyleDataResponseBean bean =
          StyleDataResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
              if(bean?.data?.list != null && onGeStyle != null){
                onGeStyle.call(bean?.data?.list);
              }
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }




  @override
  void onDisposed() {
    totalValueNotifier?.dispose();
    statusTypeValueNotifier?.dispose();
    smartHomeWaterListValueNotifier?.dispose();
    super.onDisposed();
  }


  @override
  bool isNeedCache() {
    return true;
  }


  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": page ?? 1,
      "size": 20,
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return NetApi.GET_SMART_HOME_LIST;
  }

  @override
  SmartHomeIndexResponseBean parseData(VgHttpResponse resp) {
    SmartHomeIndexResponseBean vo = SmartHomeIndexResponseBean.fromMap(resp?.data);
    FlutterGlobalMonitoringUtils?.dataNotifier?.value = vo?.code;
    loading(false);
    if((vo?.data?.page?.total??0) > 0){
      statusTypeValueNotifier?.value = null;
    }else{
      statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
    }
    totalValueNotifier.value = vo?.data?.page?.total;
    print("_storeCount:" + totalValueNotifier.value.toString());
    SharePreferenceUtil.putInt(SP_STORE_COUNT, totalValueNotifier.value);
    return vo;
  }

  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  Stream<String> get onRefreshFailed => Stream.value(null);
}
